package net.gyapp.markim.widget;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;

/**
 * Auther:  winds
 * Email:   heardown@163.com
 * Date:    2018/7/19.
 * Desc:
 */

public class IndexRecyclerView extends RecyclerView {

    public IndexRecyclerView(Context context) {
        super(context);
    }

    public IndexRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public IndexRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /**
     * 滚动到指定位置（注意：对瀑布流无效果）
     */
    public void moveToPosition(int position) {
        if (position < 0 || getAdapter() == null || getAdapter().getItemCount() <= position) {
            return;
        }
        stopScroll();
        LayoutManager manager = getLayoutManager();
        if (manager instanceof LinearLayoutManager) {
            int firstItem = ((LinearLayoutManager) manager).findFirstVisibleItemPosition();
            int lastItem = ((LinearLayoutManager) manager).findLastVisibleItemPosition();

            if (position <= firstItem) {
                this.scrollToPosition(position);
            } else if (position <= lastItem) {
                int top = this.getChildAt(position - firstItem).getTop();
                this.scrollBy(0, top);
            } else {
                this.scrollToPosition(position);
            }
        }
    }

    /**
     * 平滑滚动到指定位置（注意：对瀑布流无效果）
     */
    public void smoothMoveToPosition(int position) {
        if (position < 0 || getAdapter() == null || getAdapter().getItemCount() <= position) {
            return;
        }
        stopScroll();
        LayoutManager manager = getLayoutManager();
        if (manager instanceof LinearLayoutManager) {
            int firstItem = ((LinearLayoutManager) manager).findFirstVisibleItemPosition();
            int lastItem = ((LinearLayoutManager) manager).findLastVisibleItemPosition();
            if (position <= firstItem) {
                this.smoothScrollToPosition(position);
            } else if (position <= lastItem) {
                int top = this.getChildAt(position - firstItem).getTop();
                this.smoothScrollBy(0, top);
            } else {
                this.smoothScrollToPosition(position);

            }
        }
    }
}
